package com.iatinspur;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class MyClassLoader4Test extends ClassLoader{
    public static Map<String,Class<?>> map=new HashMap<String,Class<?>>();


    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (name.startsWith("java.lang")) {
            return super.loadClass(name);
        }

        if (name.startsWith("java.io")) {
            return super.loadClass(name);
        }
        if (name.startsWith("com.iatinspur.My")) {
            return super.loadClass(name);
        }

        Class<?> loadedClass = findClass(name);
        if (loadedClass != null) {
            System.err.println("不空");
            return loadedClass;
        }
        InputStream in = null;
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        try {
            in = new FileInputStream(new File("D:\\myClass\\MyIml.class"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        byte[] buf = new byte[1024];
        int temp;
        try {
            while((temp=in.read(buf))!=-1){
                bo.write(buf, 0, temp);
            }
        }catch (IOException e){

        }
        System.out.println(bo.toByteArray().length);
        Class<?> aClass = defineClass(name, bo.toByteArray(), 0, bo.toByteArray().length);
        map.put(name, aClass);
        return aClass;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        return map.get(name);
    }


    public  Class<?> myDefineClass(String name, byte[] b, int off, int len){
       return defineClass(name, b, off, len);
    }

}
